<template>
  <div>
    <div class="shuruk">
      <div class="jiancheng">
        <el-form ref="form" :model="form" label-width="80px">
          <el-select v-model="form.region" placeholder="入住状态">
            <el-option label="已入住" value="1"></el-option>
            <el-option label="未入住" value="2"></el-option>
          </el-select>
        </el-form>
      </div>
      <div class="inputonee">
        <el-input v-model="input1" placeholder="单元名称"></el-input>
      </div>
      <div class="inputonee">
        <el-input v-model="input2" placeholder="幢号"></el-input>
      </div>
      <div class="inputonee">
        <el-input v-model="input3" placeholder="房号"></el-input>
      </div>
      <div class="inputonee">
        <el-input v-model="input4" placeholder="住客姓名"></el-input>
      </div>
      <el-button @click="chaxun" class="anniu" type="primary"
        ><i class="el-icon-circle-plus"></i>查询</el-button
      >
      <el-button @click="exportSelect()" class="anniu" type="success"
        ><i class="el-icon-circle-plus"></i>批量导出</el-button
      >
      <el-button @click="shanchu()" class="anniu" type="primary"
        ><i class="el-icon-refresh-left"></i>批量删除</el-button
      >
    </div>
    <div class="danwei">
      <el-table
        :data="tableData"
        border
        style="width: 100%; text-align: center"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="序号">
          <template slot-scope="scope">
            {{ currPage * pageNum + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="unitname" label="单位名称">
          <template slot-scope="scope">
            {{ scope.row.unitname || "暂无" }}
          </template>
        </el-table-column>
        <el-table-column prop="buildnum" label="幢号">
          <template slot-scope="scope">
            {{ scope.row.buildnum || "暂无" }}
          </template>
        </el-table-column>
        <el-table-column prop="storeynum" label="楼层数">
          <template slot-scope="scope">
            {{ scope.row.storeynum || "暂无" }}
          </template>
        </el-table-column>
        <el-table-column prop="homenum" label="房号">
          <template slot-scope="scope">
            {{ scope.row.homenum || "暂无" }}
          </template>
        </el-table-column>
        <el-table-column prop="homename" label="住客姓名">
          <template slot-scope="scope">
            {{ scope.row.homename || "暂无" }}
          </template>
        </el-table-column>
        <el-table-column prop="unitstatus" label="状态">
          <template slot-scope="scope">
            {{ scope.row.homestatus === 1 ? "已入住" : "未入住" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="blockkk">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
const XLSX = require("xlsx");
export default {
  data() {
    return {
      input1: "",
      input2: "",
      input3: "",
      input4: "",
      form: {
        region: "",
      },
      currPage: 1,
      pageNum: 10,
      tableData: [],
      total: 0,
      token: "",
      selectdata: [],
    };
  },
  created() {
    this.getli();
    this.token = localStorage.getItem("token");
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectdata = selection;
    },
    exportSelect() {
      this.$confirm("是否确认导出选中的数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.selectdata.length <= 0) {
            this.$message.info("请选择数据！");
            return;
          }
          let tableData = [
            ["序号", "单位名称", "幢号", "楼层数", "房号", "住客姓名", "状态"],
          ];
          this.selectdata.forEach((item, index) => {
            tableData.push([
              index + 1,
              item.unitname || "",
              item.buildnum || "",
              item.storeynum || "",
              item.homenum || "",
              item.homename || "",
              item.homestatus === 1 ? "已入住" : "未入住",
            ]);
          });
          const worksheet = XLSX.utils.aoa_to_sheet(tableData);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, "房屋信息表");
          const wbout = XLSX.write(workbook, {
            bookType: "xlsx",
            type: "array",
          });
          const blob = new Blob([wbout], { type: "application/octet-stream" });
          const link = document.createElement("a");
          link.href = URL.createObjectURL(blob);
          link.download = `选中的房屋信息_${this.timeFormat()}.xlsx`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
        })
        .catch(() => {});
    },
    timeFormat() {
      let time = new Date();
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let date = time.getDate();
      let hours = time.getHours();
      let minutes = time.getMinutes();
      let seconds = time.getSeconds();
      return (
        year +
        "-" +
        this.addZero(month) +
        "-" +
        this.addZero(date) +
        " " +
        this.addZero(hours) +
        ":" +
        this.addZero(minutes) +
        ":" +
        this.addZero(seconds)
      );
    },
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },

    async getchakan() {
      let res = await this.$axios.get(
        `http://community.byesame.com/house/searchnumList?homestatus=${this.form.region}&unitname=${this.input1}&buildnum=${this.input2}&homenum=${this.input3}&homename=${this.input4}&currPage=${tis.currPage-1}&pageNum=${this.pageNum}&token=${this.token}`
      );
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.$router.push({
        path: "/house/guanbian",
        query: { id: row.id },
      });
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getdel(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getdel(id) {
      let res = await this.$axios.get(
        `http://community.byesame.com/house/delunitList?id=${id}&token=${this.token}`
      );
      console.log(res);
      this.getli();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = val;
      this.getli();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currPage = val;
      this.getli();
    },
    async getli() {
      let res = await this.$axios.get(
        `http://community.byesame.com/house/gethouseList?currPage=${this.currPage-1}&pageNum=${this.pageNum}`
      );
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    },
    chaxun() {
      this.getchakan();
    },
    async shanchu() {
      if (this.selectdata.length === 0) {
        this.$message.info("请选择要删除的数据！");
        return;
      }

      try {
        await this.$confirm("此操作将永久删除选中数据，是否继续？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const idsParams = this.selectdata
          .map((item) => `ids[]=${item.id}`)
          .join("&");
        const tokenParam = `&token=${this.token}`;
        const fullParams = idsParams + tokenParam;
        const res = await this.$axios.get(
          `http://community.byesame.com/house/delnumList?${fullParams}`
        );

        this.$message.success("批量删除成功！");
        this.getli();
      } catch (error) {
        if (error === "cancel") {
          this.$message.info("已取消删除");
        } else {
          this.$message.error("删除失败，请重试");
          console.error("删除接口错误：", error);
        }
      }
    },
  },
};
</script>

<style scoped>
.shuruk .inputonee {
  width: 13.625rem;
  display: inline-block;
  margin-left: 1.25rem;
}
.block {
  display: inline-block;
  margin-left: 1.25rem;
}
.jiancheng {
  display: inline-block;
  margin-left: 1.25rem;
}
.anniu {
  width: 6.25rem;
  height: 2.5rem;
  /* line-height: 3.125rem; */
  margin-left: 1.875rem;
}
.danwei {
  margin-top: 1.875rem;
}
.blockkk {
  /* text-align: right; */
  float: right;
  margin-top: 1.875rem;
}
</style>